import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_study/http/Api.dart';
import 'package:flutter_study/http/HttpHelper.dart';
import 'package:flutter_study/http/wx_office_bean_entity.dart';
import 'package:flutter_study/utils/Toast.dart';

class DioPage extends StatefulWidget {
  @override
  _DioPageState createState() => _DioPageState();
}

class _DioPageState extends State<DioPage> {
  var mList = <WxOfficeBeanEntity>[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Dio网络请求"),
        ),
        body: ListView(
          children: [
            TextButton(
              onPressed: () {
                getData(context);
              },
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.red),
                  foregroundColor: MaterialStateProperty.all(Colors.white)),
              child: Text("get请求"),
            ),
            TextButton(
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.red),
                  foregroundColor: MaterialStateProperty.all(Colors.white)),
              onPressed: () {
                _postData(context);
              },
              child: Text("post请求"),
            ),
            ListView(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              children: mList.map((e) {
                return ListTile(
                  title: Text(e.name),
                );
              }).toList(),
            )
          ],
        ));
  }

  void getData(BuildContext context) {
    CancelToken cancelToken = CancelToken();
    HttpHelper.instance.getHttp<List<WxOfficeBeanEntity>>(Api.MP_WECHAT_NAMES,
        cancelToken: cancelToken, onSuccess: (data) {
      setState(() {
        mList.clear();
        mList.addAll(data.data);
        Toast.toast(context, msg: "请求成功");
      });
    }, onError: (message) {
      Toast.toast(context, msg: message);
      print("onError" + message);
    });
  }
}

/// post请求
_postData(BuildContext context) {
  Map<String, dynamic> map = Map();
  map.putIfAbsent("username", () => "123456");
  map.putIfAbsent("password", () => "123456");
  HttpHelper.instance.postHttp(Api.LOGIN,
      parameters: map, method: HttpHelper.POST, onSuccess: (data) {
    Toast.toast(context, msg: data.toString());
  }, onError: (message) {
    Toast.toast(context, msg: message);
  });
}
